package com.csmy.my.center.util.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.attilax.ioc.IocXq214;
import com.attilax.sso.LoginX;
import com.attilax.token.TokenService;
import com.csmy.my.center.module.MemeberInfo;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.RequestUtil;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
import com.csmy.my.center.util.db.JdbcTemplateTool;
import com.google.inject.Inject;

public class UserLoginServlet extends HttpServlet {
	@Inject
	TokenService tokSvr;
	private Logger logger = Logger.getLogger(UserLoginServlet.class);
	private static final long serialVersionUID = 392477463616513615L;
	public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String errorMsg = "";
		String returnMsg = "";
		HttpSession session = req.getSession();
		//处理注册逻辑
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String captcha = req.getParameter("captcha");
		String ismobile = req.getParameter("ismobile");
		String exp_version = req.getParameter("ieversion");
		String path = req.getContextPath();
		try {
			
			if(StringUtil.isNotEmpty(username) && StringUtil.isNotBlank(password)){//处理登录操作
				
				logger.info("开始验证用户登录信息..............");
				//过滤参数 防止注入
				username = (username); //ati p7j canel filt
				password = CTUtils.specialStrFilter(password);
				captcha = CTUtils.specialStrFilter(captcha);
				// 组织登录参数
				Dto pDto = new BaseDto();
				pDto.put("login_name", username);
				pDto.put("login_pword", CTUtils.encryptBasedDes(password));
				//去掉 验证码
				/*if(StringUtil.isNotBlank(captcha)){
					if (!captcha.equalsIgnoreCase((String)session.getAttribute(CTConstants.SESSION_CODE))) {
						logger.error("帐户[" + username + "]登陆失败.(失败原因：验证码错误!)");
						errorMsg = "验证码输入错误,请重新输入！";
						returnMsg = "false#"+errorMsg;
						return;
					}
				}*/
				
				// 开始获取用户信息进行验证
				MemeberInfo userInfo = JdbcTemplateTool.checkMUserLogin(pDto);
				if (CTUtils.isEmpty(userInfo)) {
					userInfo = JdbcTemplateTool.checkMUserLogin(pDto);
					if (CTUtils.isEmpty(userInfo)) {
					logger.error("帐户[" + username + "]登陆失败:帐号或密码输入错误,请重新输入");
					errorMsg = "帐号或密码输入错误,请重新输入！";
					returnMsg = "false#"+errorMsg;
					return;
					}
				}
				// 判断密码
				if (!CTUtils.encryptBasedDes(password).equals(userInfo.getPassword())) {
					logger.error("帐户[" + username + "]登陆失败.(失败原因：密码输入错误!)");
					errorMsg = "密码输入错误,请重新输入！";
					returnMsg = "false#"+errorMsg;
					return;
				}

				
				// 加入用户未加密的密码
				returnMsg = "true#登录成功";
				userInfo.setEpassword(CTUtils.decryptBasedDes(userInfo.getPassword()));
				session.setAttribute(CTConstants.SESSION_MUSER, userInfo);
				
				//q32
				if(tokSvr==null)
					tokSvr=IocXq214.getBean(TokenService.class);
				tokSvr.setModule("userMod");
				System.out.println("---");
				tokSvr.setToken(userInfo.getAccount(), userInfo.getMemeber_id(), resp);
				//
				
				//记录登录日志
				Dto logDto = new BaseDto();
				logDto.put("user_id", userInfo.getMemeber_id());
				if(req.getRemoteAddr().equals("0:0:0:0:0:0:0:1")){
			 	   logDto.put("login_ip", "127.0.0.1");
				}else{
				   logDto.put("login_ip", req.getRemoteAddr());
				}
				logDto.put("login_time", CTUtils.getCurrentTime());
				if(ismobile.equals("2")||ismobile.equals("3")){
					logDto.put("ismobile", "1");
				}else{
				    logDto.put("ismobile", "0");
				}
				logDto.put("log_type", "0");
				logDto.put("exp_version", exp_version);
				JdbcTemplateTool.addLoginLog(logDto);
				
				//更新登录时间
				Dto upDto = new BaseDto();
				upDto.put("update_time", CTUtils.getCurrentTime());
				upDto.put("memeber_id", userInfo.getMemeber_id());
				JdbcTemplateTool.updateMemeberInfo(upDto);

			}else{
				
				//如果已经登录就跳到主页
				if(CTUtils.isNotEmpty(req.getSession().getAttribute(CTConstants.SESSION_MUSER))){
					logger.error("会员已登录，进入会员主页....");
					CTUtils.getParamToReq(req);
					resp.sendRedirect(RequestUtil.getBasePath(req)+"/user/index");
				}else{
					logger.error("会员返回重新登录....");
					CTUtils.getParamToReq(req);
				    req.getRequestDispatcher("/wxb/memlogin.jsp").forward(req, resp);
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			returnMsg = "false#用户账户或密码错误";
		}finally{
			RequestUtil.renderText(returnMsg);
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	

}
